<?php

namespace App\Http\Controllers\Api;

use App\Exceptions\ResponseException;
use App\Handler\ImageHandler;
use App\Http\Requests\Api\User\SendMsgRequest;
use App\Http\Requests\Api\User\UpdatePswdRequest;
use App\Http\Requests\Api\User\UpdateRequest;
use App\Models\Region;
use App\Models\User;
use App\Models\UserAddress;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Whoops\Exception\ErrorException;

class UserController extends BaseController
{
    use ImageHandler;

    /**
     * 个人中心首页
     * User: ihome
     */
    public function index()
    {
        if ($user = auth('api')->user()) { //存在并且不是锁定用户
            if ($user->status == 2) {
                throw new ResponseException(404, '用户不存在或已锁定');
            }

            //获得用户的基本信息
            $user_info = [
                'thumb'     => $user['thumb'],
                'tel'       => $user['tel'],
                'nick_name' => $user['nick_name'],
                'balance' => $user['balance']
            ];

            $user_info['coupons'] = auth('api')->user()->coupons()->count();//优惠券数量

            //用户的订单信息
            $order_info = [
                'not_pay'      => auth('api')->user()->order()->where(['status' => 0])->count(),
                'not_send'     => auth('api')->user()->order()->where(['status' => 1])->count(),
                'already_send' => auth('api')->user()->order()->where(['status' => 2])->count(),
                'not_comment'  => auth('api')->user()->order()->where(['status' => 3])->count(),
                'after_server' => auth('api')->user()->order()->whereIn('status', [5, 6])->count(),//售后订单是申请了和处理中的。处理完成的不进行记录

            ];

            $data = [
                'order_info' => $order_info,
                'user_info'  => $user_info,
            ];
            throw new ResponseException(200, 'ok', $data);
        } else {
            throw new ResponseException(404, '用户不存在或已锁定');
        }
    }

    /**
     * 用户信息
     * User: Clannad ~ ☆
     * DateTime: 2019/11/1 18:48
     * @throws ResponseException
     */
    public function user_info()
    {
        if ($user = auth('api')->user()) {

            $data['username']  = $user['username'];
            $data['nick_name'] = $user['nick_name'];
            $data['thumb']     = $user['thumb'];
            $data['tel']       = $user['tel'];
            $data['email']     = $user['email'];

            //旧写法
//			$userinfo = User::with(['user_info'])->find($user['id'])->toArray();

            $data['age'] = auth('api')->user()->user_info->age;
            $data['sex'] = auth('api')->user()->user_info->sex;

            throw new ResponseException(200, 'ok', $data);
        } else {
            throw new ResponseException(404, '用户不存在');
        }
    }

    /**
     * 修改用户信息
     * User: Clannad ~ ☆
     * DateTime: 2019/11/1 19:31
     */
    public function update(UpdateRequest $request)
    {
        $upData = $request->all();

        if ($user = User::find(auth('api')->id())) {

            $user->fill($upData);
            $user->update();

            $user->user_info()->update([
                'age' => $upData['age'],
                'sex' => $upData['sex'],
            ]);

            $userData = [
                'nick_name' => $user->nick_name,
                'sex'       => $user->user_info->sex,
                'age'       => $user->user_info->age,
            ];

            throw new ResponseException(200, '更新成功', $userData);
        } else {
            throw new ResponseException(404, '用户不存在');
        }
    }


    /**
     * 用户密码修改 分成几步  (旧版)
     * 1.用户输入手机号 获取验证码 后端发送验证码后，生成一个随机串缓存，并把随机串给前端
     * 2.跳转到第二个页面，用户收入手机验证码，旧密码，新密码，确认新密码，随机串一起提交
     * 3.验证新密码与确认密码的一致性，验证旧密码的一致性，验证随机串取出验证码校验
     * 4.第三点全部通过时，修改密码，否则抛出异常
     * User: Clannad ~ ☆
     * DateTime: 2019/11/1 19:32
     */

    /**
     * 修改登录密码
     * User: ihome
     */
    public function changePswd(UpdatePswdRequest $request)
    {
        $password   = $request->input('password');
        $verify_str = $request->input('verify_str');

        if ($user_id = Redis::get($verify_str)) {
            if ($user_id != auth('api')->id()) {
                throw new ResponseException(400, '用户非法，修改失败');
            }

            //开始修改密码
            auth('api')->user()->update([
                'password' => bcrypt($password)
            ]);

            throw new ResponseException(200, '修改成功');
        } else {
            throw new ResponseException(400, '修改密码验证码已失效，请重新发送验证码');
        }

    }


    /**
     * 用户评论列表
     * User: Clannad ~ ☆
     * DateTime: 2019/11/2 14:35
     */
    public function commets()
    {
        $user        = auth('api')->user();
        $commentList = $user
            ->comment()
            ->select(['id', 'content', 'created_at', 'article_id'])
            ->with(['article' => function ($query){
                return $query->select('title', 'id')->first();
            }])
            ->get()
            ->map(function ($comment){
                return [
                    'id'         => $comment->id,
                    'content'    => $comment->content,
                    'created_at' => $comment->created_at->toDateTimeString(),
                    'article_id' => $comment->article_id,
                    'title'      => $comment->article->title,
                ];
            })->toArray();

        if ($commentList) {
            throw new ResponseException(200, 'ok', $commentList);
        } else {
            throw new ResponseException(404, '您没有评论任何文章');
        }

    }

    /**
     * 上传文件
     * User: ihome
     */
    public function uploadThumb(Request $request)
    {
//        $img = $this->uploadImg('uploads/user/thumb','thumb',);
        if ($request->hasFile('thumb')) {
//            $img = $this->imageUploader('uploads/user/thumb', 'thumb', auth('api')->id() . '_');
            $img = $this->upLoadToAliOss('thumb','user/',auth('api')->id() . '_');

            if ($img['status'] == 200) {
                //更新用户头像

//                $thumb = getHttpType() . $_SERVER['SERVER_NAME'] . '/' . $img['path'];

				$orgThumb = auth('api')->user()->thumb;

                auth('api')->user()->update([
                    'thumb' => $img['path'],
                ]);

                //删除原图
				$file_name = $this->cutFileName($orgThumb);
				$this->delAliOssFile($file_name);

                throw new ResponseException(200, 'ok', $img['path']);
            } else {
                throw new ResponseException(400, $img['msg']);
            }
        } else {
            throw new ResponseException(400, '没有上传文件');
        }
    }

    /**
     * 发送短信
     * User: ihome
     */
    public function sendMsg(SendMsgRequest $request)
    {
        //判断是否已经发送了数据
        $tel = $request->input('tel');

        $hashKey = 'send_msg:' . auth('api')->id() . ":" . $tel;

        //已经发送的时候返回
        if ($sendInfo = Redis::hgetall($hashKey)) {
            $returnData = [
                'send_status' => 1,
                'calcSecond'  => $sendInfo['send_time'] + 100 - time(),//100秒倒计时
                'verify_str'  => $sendInfo['rand_str'] //验证码的随机串
            ];

            throw new ResponseException(200, '已经发送过了', $returnData);
        }

        //未发送的时候
        $code    = mt_rand(100000, 999999);
        $content = '您的验证码为：' . $code;
        $to      = auth('api')->user()->email;

        \Mail::raw($content, function ($message) use ($to){
            $message->to($to)->subject('【验证码】-- Clannad商城');
        });

        //生成一个随机字符串
        $randStr = time() . mt_rand(22, 99) . '_rand_str';

        //将验证码存入到redis中
        $sendInfo = [
            'send_time' => time(),
            'rand_str'  => $randStr //验证码的随机串
        ];

        //存入redis
        Redis::hmset($hashKey, $sendInfo);
        Redis::expire($hashKey, 100); //60秒有效期

        Redis::setex($randStr, 300, $code);//设置这个key的有效期是300秒
        //返回

        throw new ResponseException(200, '发送成功', ['verify_str' => $randStr]);
    }

    /**
     * 检查验证码
     * User: ihome
     */
    public function checkCode(Request $request)
    {
        $code       = $request->input('sms_code');
        $tel        = $request->input('tel');
        $verify_str = $request->input('verify_str');

        $verify_code = Redis::get($verify_str);

        if ( ! $verify_code) {
            throw new ResponseException(400, '该验证码已过期，请重新发送');
        }

        if ($verify_code != $code) {
            throw new ResponseException(400, '验证码不正确');
        } else {
            $hashKey = 'send_msg:' . auth('api')->id() . ":" . $tel;
            Redis::del($verify_str);//确认完就清除掉
            Redis::del($hashKey);//确认完就清除掉

            //设置一个新的缓存，给修改密码的时候用的 时间是10分钟有效 10分钟后，不可再修改密码 需重新来过
            $rand_str = mt_rand(1111, 9999) . time() . '_rand_set_pswd';
            Redis::setex($rand_str, 600, auth('api')->id());//存入用户id 用于效验

            throw new ResponseException(200, 'ok', $rand_str);
        }
    }

    /**
     * 用户地址列表
     * User: Clannad ~ ☆
     */
    public function userAddrList()
    {
        $query = UserAddress::query()
                        ->select('user_address.id','username','tel','address','default',
                            \DB::raw('REPLACE(my_region.whole_name,"中国,","") as area')
                        )
                        ->leftJoin('region','region.county_id','=','user_address.county_id')
                        ->where('user_id',auth('api')->id())
                        ->orderBy('default','desc')
                        ->groupBy('user_address.id');

//                        ->get()->toArray();

        $result = \DB::table(\DB::raw("({$query->toSql()}) as areas"))
            ->mergeBindings($query->getQuery())
            ->select('id','username','tel','address','default',
            \DB::raw('REPLACE(area,",","") as area')
            )->get()->toArray();
//        $res = UserAddress::query()->select('*')->joinSub($query,'lists')->get();

        throw new ResponseException(200,'ok',$result);
    }

    /**
     * 用户地址添加
     * User: Clannad ~ ☆
     * @param Request $request
     * @throws ResponseException
     */
    public function userAddressAdd(Request $request)
    {
        $area    = $request->input('area');
        $defalut = $request->input('default');

        $user_id = auth('api')->id();
        $data = [
            'username' => $request->input('username'),
            'tel'      => $request->input('tel'),
            'address'  => $request->input('address'),
            'default'  => $defalut
        ];

        $area = explode('/', $area);

        $area_ids = [];

        foreach ($area as $k => $v) {
            $area_id = Region::query()->where('area_name', $v)->value('id');

            if ( ! $area_id) {
                throw new ResponseException(400, '地址添加失败，所在区域数据存在差异，请联系管理员--' . $v);
            } else {
                $area_ids[] = $area_id;
            }
        }

        $data['user_id']     = $user_id;
        $data['province_id'] = $area_ids['0'];
        $data['city_id']     = $area_ids['1'];
        $data['county_id']   = $area_ids['2'];

        \DB::beginTransaction();

        try{
            $res = UserAddress::create($data);

            if($defalut){
                //把其他更新为非默认
                UserAddress::query()
                    ->where('user_id','=',$user_id)
                    ->where('id','!=',$res->id)->update([
                        'default'=>0
                    ]);
            }else{
                //判断用户地址条数，如果只有一条，那么，就将这一条设置成默认
                $checkNum = UserAddress::query()->where('user_id',$user_id)->count();

                if($checkNum == 1){
                    UserAddress::query()->where('id',$res->id)->update(['default'=>1]);
                }
            }


            \DB::commit();
            throw new ResponseException(200,'添加成功');
        }catch (ErrorException $exception){
            \DB::rollBack();
            \Log::info($exception->getMessage());
            throw new ResponseException(500,'添加失败，请联系管理员');
        }
    }

    /**
     * 用户地址编辑
     * User: Clannad ~ ☆
     * Date: 2020/2/24 0024 9:33
     */
    public function userAddressEdit()
    {
        $id = request()->input('id');

        $query = UserAddress::query()
            ->select('user_address.id','username','tel','address','default',
                \DB::raw('REPLACE(my_region.whole_name,"中国,","") as area')
            )
            ->leftJoin('region','region.county_id','=','user_address.county_id')
            ->where([
                'user_id'=>auth('api')->id(),
                'user_address.id'=>$id,
            ])
            ->orderBy('default','desc')
            ->groupBy('user_address.id');

        $address = \DB::table(\DB::raw("({$query->toSql()}) as areas"))
            ->mergeBindings($query->getQuery())
            ->select('id','username','tel','address','default',
                \DB::raw('REPLACE(area,",","/") as area')
            )->get();

        if(!$address){
            throw new ResponseException(404,'没有找到该地址');
        }else{
            $address = $address->toArray();
        }

        throw new ResponseException(200,'ok',$address['0']);
    }


    /**
     * 用户地址更新
     * User: Clannad ~ ☆
     * Date: 2020/2/24 0024 23:00
     * @param Request $request
     * @throws ResponseException
     */
    public function userAddressUpdate(Request $request)
    {
        $area    = $request->input('area');
        $defalut = $request->input('default');
        $id      = $request->input('id');

        $userAddress = UserAddress::find($id);

        if(!$userAddress){
            throw new ResponseException(404,'用户地址不存在');
        }

        $user_id = auth('api')->id();
        $data = [
            'username' => $request->input('username'),
            'tel'      => $request->input('tel'),
            'address'  => $request->input('address'),
            'default'  => $defalut
        ];

        $area = explode('/', $area);

        $area_ids = [];

        foreach ($area as $k => $v) {
            $area_id = Region::query()->where('area_name', $v)->value('id');

            if ( ! $area_id) {
                throw new ResponseException(400, '地址添加失败，所在区域数据存在差异，请联系管理员---'.$v);
            } else {
                $area_ids[] = $area_id;
            }
        }


        $data['user_id']     = $user_id;
        $data['province_id'] = $area_ids['0'];
        $data['city_id']     = $area_ids['1'];
        $data['county_id']   = $area_ids['2'];

        \DB::beginTransaction();

        try{
            UserAddress::query()->where('id',$id)->update($data);

            if($defalut){
                //把其他更新为非默认
                UserAddress::query()
                    ->where('user_id','=',$user_id)
                    ->where('id','!=',$id)->update([
                        'default'=>0
                    ]);
            }

            \DB::commit();
            throw new ResponseException(200,'修改成功');
        }catch (ErrorException $exception){
            \DB::rollBack();
            \Log::info($exception->getMessage());
            throw new ResponseException(500,'修改失败，请联系管理员');
        }
    }

    /**
     * 删除用户地址
     * User: Clannad ~ ☆
     */
    public function delAddress(Request $request)
    {
        $id =$request->input('id');
        $address = UserAddress::query()->where([
                        'user_id'=>auth('api')->id()
                    ])->find($id);

        if(!$address){
            throw new ResponseException(404,'地址不存在');
        }

        $address->delete();

        throw new ResponseException(200,'删除成功');
    }
}
